#include "thread_pool.h"
extern char pre_cwd[1024];
extern char cur_cwd[1024];
extern char server_cwd[1024];

/*
   Eddie made cdCommand
   */
void cdCommand(task_t * task)
{
    //记录当前程序的工作目录
    char cwd[1024] = {0};
    if(getcwd(cwd,sizeof(cwd)) == NULL){
        error(1,errno,"getcwd");
    } 
    //先获取将要改变的工作路径
    char path[1024] = {0};
    sprintf(path,"%s/%s",cwd,task->data);
    //如果path是.. 先判断当前路径是否为serve端所在的目录
    if(!strcmp(task->data,"..")){
        if(!strcmp(cwd,server_cwd)){
            //如果是当前目录，就显示cd失败
            printf("You are in the top-level directory and cannot enter the previous directory\n");
        }else{
            //退回父目录
            //重置pre和cur
            if(getcwd(pre_cwd,sizeof(pre_cwd)) == NULL){
                error(1,errno,"getcwd");
            }            
            int ret = chdir(path);
            if(ret == -1){
                printf("You don't have permission to access this dir %s\n",task->data);
            }
            if(getcwd(cur_cwd,sizeof(cur_cwd)) == NULL){
                error(1,errno,"getcwd");
            }
        }
    }else if(!strcmp(task->data,".")){
    }else if(!strcmp(task->data,"-")){
        //退回上一次操作的目录
        int ret = chdir(pre_cwd);
        if(ret == -1){
            printf("You don't have permission to access this dir %s\n",task->data);
        }
        //交换pre和cur
        char temp[1024] = {0};
        strcpy(temp,cur_cwd);
        puts(temp);
        strcpy(cur_cwd,pre_cwd);
        strcpy(pre_cwd,temp);
    }else if(!strcmp(task->data,"~")){
        int ret = chdir(server_cwd);
        if(ret == -1){
            printf("You don't have permission to access this dir %s\n",task->data);
        }
        strcpy(pre_cwd,cur_cwd);
        strcpy(cur_cwd,server_cwd);
    }else{
        int ret = chdir(path);
        if(ret == -1){
            printf("cd: %s not exist\n",task->data);
            
        }else {
        //更新当前目录和之前的目录
        strcpy(pre_cwd,cur_cwd);
        strcpy(cur_cwd,path);
        }
    }
}

